<template>
  <div class="purchase-order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>进货订单</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="进货单号">
            <el-input
              v-model="searchForm.orderCode"
              placeholder="请输入进货单号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="单据状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="草稿" :value="0" />
              <el-option label="已提交" :value="1" />
              <el-option label="已审核" :value="2" />
              <el-option label="已完成" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select
              v-model="searchForm.supplierId"
              placeholder="请选择供应商"
              clearable
              filterable
              style="width: 200px"
              :loading="supplierLoading"
            >
              <el-option
                v-for="supplier in supplierList"
                :key="supplier.id"
                :label="supplier.name"
                :value="supplier.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="进货日期">
            <el-date-picker
              v-model="searchForm.orderDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-card class="table-card">
        <template #header>
          <div class="table-header">
            <span>进货订单列表</span>
            <div class="table-actions">
              <el-button type="success" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                新增订单
              </el-button>
              <el-button type="primary" @click="handleRefresh" :loading="loading">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          border
          style="width: 100%"
          :height="tableHeight"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          
          <el-table-column prop="orderCode" label="进货单号" width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <el-link type="primary" @click="handleViewDetail(row)">
                {{ row.orderCode }}
              </el-link>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="单据状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="orderDate" label="进货日期" width="120" />
          
          <el-table-column prop="supplierName" label="供应商" width="150">
            <template #default="{ row }">
              {{ row.supplierName }}
            </template>
          </el-table-column>
          
           <el-table-column prop="contact" label="联系人" width="100" show-overflow-tooltip />
           
           <el-table-column prop="contactPhone" label="联系方式" width="120" />
           
           <el-table-column prop="deptName" label="进货部门" width="120" show-overflow-tooltip />
           
           <el-table-column prop="creator" label="进货人" width="100" />
          
          <el-table-column prop="totalQuantity" label="货品数量" width="100" align="right">
            <template #default="{ row }">
              {{ row.totalQuantity || 0 }}
            </template>
          </el-table-column>
          
          <el-table-column label="货品金额" width="120" align="right">
            <template #default="{ row }">
              ¥{{ formatAmount(row.totalAmount) }}
            </template>
          </el-table-column>
          
          <!-- 进货货品列 - 已修改为使用purchaseGoods字段适配后端数据结构 -->
          <el-table-column prop="purchaseGoods" label="进货货品" width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.purchaseGoods && row.purchaseGoods.trim() !== ''">
                {{ getGoodsSummary(row.purchaseGoods) }}
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="creator" label="制单人" width="100" />
          
          <el-table-column prop="deptId" label="所在部门" width="120" show-overflow-tooltip />
          
          <el-table-column prop="createDate" label="制单时间" width="160" />
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 获取实例
const { proxy } = getCurrentInstance()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const supplierList = ref([])
const supplierLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  orderCode: '',
  status: '',
  supplierId: '',
  orderDate: ''
})

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 表格高度计算
const tableHeight = computed(() => {
  return window.innerHeight - 400
})

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',    // 草稿
    1: 'warning', // 已提交
    2: 'success', // 已审核
    3: 'primary'  // 已完成
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已提交',
    2: '已审核',
    3: '已完成'
  }
  return statusMap[status] || '未知'
}

// 格式化金额
const formatAmount = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toFixed(2)
}

// 获取货品摘要 - 适配后端purchaseGoods字段
const getGoodsSummary = (purchaseGoods) => {
  console.log('getGoodsSummary 接收到的数据:', purchaseGoods)
  console.log('数据类型:', typeof purchaseGoods)
  
  // 如果数据为空或不是字符串，返回默认值
  if (!purchaseGoods || typeof purchaseGoods !== 'string' || purchaseGoods.trim() === '') {
    console.log('purchaseGoods为空或不是有效字符串')
    return '-'
  }
  
  try {
    // 尝试解析JSON字符串
    let items = []
    
    // 如果是JSON字符串，解析它
    if (purchaseGoods.startsWith('[') || purchaseGoods.startsWith('{')) {
      console.log('尝试解析JSON字符串:', purchaseGoods)
      const parsed = JSON.parse(purchaseGoods)
      
      // 如果是数组，直接使用
      if (Array.isArray(parsed)) {
        items = parsed
      }
      // 如果是对象，可能包含items字段
      else if (parsed.items && Array.isArray(parsed.items)) {
        items = parsed.items
      }
      // 如果是单个对象，包装成数组
      else if (typeof parsed === 'object') {
        items = [parsed]
      }
    }
    // 如果是逗号分隔的字符串，按逗号分割
    else if (purchaseGoods.includes(',')) {
      console.log('按逗号分割字符串:', purchaseGoods)
      items = purchaseGoods.split(',').map(name => ({ goodsName: name.trim() }))
    }
    // 如果是单个货品名称
    else {
      console.log('单个货品名称:', purchaseGoods)
      items = [{ goodsName: purchaseGoods.trim() }]
    }
    
    console.log('解析后的items:', items)
    
    if (!items || items.length === 0) {
      console.log('解析后items为空')
      return '-'
    }
    
    const names = items.map(item => {
      console.log('处理货品项:', item)
      return item.goodsName || item.name || item.productName || item.specification || '未知货品'
    })
    
    console.log('提取的货品名称:', names)
    
    if (names.length <= 3) {
      return names.join('、')
    } else {
      return names.slice(0, 3).join('、') + `等${names.length}项...`
    }
  } catch (error) {
    console.error('解析purchaseGoods失败:', error)
    console.log('原始数据:', purchaseGoods)
    
    // 如果JSON解析失败，尝试按逗号分割
    if (purchaseGoods.includes(',')) {
      const names = purchaseGoods.split(',').map(name => name.trim())
      if (names.length <= 3) {
        return names.join('、')
      } else {
        return names.slice(0, 3).join('、') + `等${names.length}项...`
      }
    }
    
    // 如果都失败了，直接返回原始字符串（截取前50个字符）
    return purchaseGoods.length > 50 ? purchaseGoods.substring(0, 50) + '...' : purchaseGoods
  }
}

// 获取供应商名称
const getSupplierName = (supplierId) => {
  if (!supplierId) return '-'
  const supplier = supplierList.value.find(s => s.id === supplierId)
  return supplier ? supplier.name : `ID: ${supplierId}`
}

// 获取供应商列表
const fetchSupplierList = async () => {
  supplierLoading.value = true
  try {
    // 直接从供应商表获取数据
    const params = {
      pageIndex: 1,
      pageSize: 1000
      // 暂时不添加状态过滤，先获取所有供应商
    }
    
    console.log('正在获取供应商数据...', params)
    const response = await proxy.http.post('/api/suppliermodel/GetPageData', params, false)
    
    console.log('供应商API响应:', response)
    
    // 检查响应是否成功 - 在这个系统中，status: 0 可能表示成功
    if (response && (response.status === 0 || response.status === true || response.status === 1)) {
      // 处理不同的数据格式
      let data = []
      
      // 优先检查直接的数据路径
      if (response.rows && Array.isArray(response.rows)) {
        data = response.rows
        console.log('从 response.rows 获取数据')
      } else if (response.data?.data && Array.isArray(response.data.data)) {
        data = response.data.data
        console.log('从 response.data.data 获取数据')
      } else if (response.data?.rows && Array.isArray(response.data.rows)) {
        data = response.data.rows
        console.log('从 response.data.rows 获取数据')
      } else if (Array.isArray(response.data)) {
        data = response.data
        console.log('从 response.data 获取数据')
      }
      
      console.log('原始供应商数据:', data)
      
      if (data.length > 0) {
        // 映射数据格式
        supplierList.value = data.map(item => ({
          id: item.Id || item.id,
          name: item.SupplierName || item.supplierName || item.name
        })).filter(item => item.id && item.name) // 过滤掉无效数据
        
        console.log('处理后的供应商数据:', supplierList.value)
        
        if (supplierList.value.length === 0) {
          ElMessage.warning('暂无有效的供应商数据')
        }
      } else {
        console.log('API响应中没有找到数据')
        ElMessage.warning('暂无供应商数据')
        supplierList.value = []
      }
    } else {
      console.error('供应商API响应错误:', response)
      ElMessage.error(response?.msg || response?.message || '获取供应商列表失败')
      supplierList.value = []
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error)
    
    // 提供更详细的错误信息
    let errorMessage = '获取供应商列表失败'
    if (error.response) {
      errorMessage = `服务器错误: ${error.response.status}`
    } else if (error.request) {
      errorMessage = '网络连接失败，请检查网络设置'
    } else {
      errorMessage = `请求错误: ${error.message}`
    }
    
    ElMessage.error(errorMessage)
    supplierList.value = []
  } finally {
    supplierLoading.value = false
  }
}

// 获取数据 - 已修改为使用InboundManagement API统一接口
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    // 清理空值参数并转换数据类型
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      } else if (key === 'supplierId' && params[key]) {
        // 确保supplierId是数字类型
        params[key] = parseInt(params[key])
        if (isNaN(params[key]) || params[key] <= 0) {
          delete params[key]
        }
      } else if (key === 'status' && params[key] !== '') {
        // 确保status是数字类型
        params[key] = parseInt(params[key])
        if (isNaN(params[key])) {
          delete params[key]
        }
      }
    })

    console.log('发送的查询参数:', params) // 调试日志
    console.log('使用InboundManagement API查询进货订单列表')
    
    // 使用项目配置的http方法 - 统一使用InboundManagement API
    const response = await proxy.http.get('/api/InboundManagement/GetPurchaseOrderPageList', params, false)

    console.log('API响应:', response) // 调试日志

    if (response && response.status) {
      // 根据API文档，数据结构是 response.data.data
      tableData.value = response.data?.data || []
      pagination.total = response.data?.total || 0
      console.log('表格数据:', tableData.value)
      console.log('总数:', pagination.total)
      
      // 调试：检查第一个订单的货品信息
      if (tableData.value.length > 0) {
        console.log('第一个订单的完整数据:', tableData.value[0])
        console.log('第一个订单的purchaseGoods字段:', tableData.value[0].purchaseGoods)
        console.log('purchaseGoods字段类型:', typeof tableData.value[0].purchaseGoods)
        console.log('第一个订单的所有字段:', Object.keys(tableData.value[0]))
      }
    } else {
      console.error('InboundManagement API调用失败，尝试使用备用API')
      ElMessage.warning('正在尝试备用查询方式...')
      
      // 如果InboundManagement API失败，尝试使用原来的API
      try {
        const fallbackResponse = await proxy.http.get('/api/PurchaseOrderModel/GetPageList', params, false)
        console.log('备用API响应:', fallbackResponse)
        
        if (fallbackResponse && fallbackResponse.status) {
          tableData.value = fallbackResponse.data?.data || []
          pagination.total = fallbackResponse.data?.total || 0
          console.log('使用备用API获取数据成功')
        } else {
          ElMessage.error(fallbackResponse?.message || '获取数据失败')
          tableData.value = []
          pagination.total = 0
        }
      } catch (fallbackError) {
        console.error('备用API也失败:', fallbackError)
        ElMessage.error('获取数据失败，请检查网络连接')
        tableData.value = []
        pagination.total = 0
      }
    }
  } catch (error) {
    console.error('获取进货订单数据失败:', error)
    ElMessage.error('获取数据失败，请检查网络连接')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.pageIndex = 1
  fetchData()
}

// 新增订单
const handleAdd = () => {
  router.push('/purchase-order/add')
}

// 刷新
const handleRefresh = () => {
  fetchData()
}

// 查看详情
const handleViewDetail = (row) => {
  ElMessage.info(`查看订单详情: ${row.orderCode}`)
  // 这里可以跳转到详情页面或打开详情弹窗
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.pageIndex = page
  fetchData()
}

// 组件挂载时获取数据
onMounted(async () => {
  // 先获取供应商列表，再获取订单数据
  await fetchSupplierList()
  fetchData()
})
</script>

<style scoped>
.purchase-order-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-section {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 搜索表单样式 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 分页样式 */
:deep(.el-pagination) {
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .purchase-order-container {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
    margin-right: 0;
  }
  
  .table-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
</style>
